package com.orhon.smartcampus.modules.baseinfo.fetcher;


import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.baseinfo.dao.SchoolcalendarWeekDao;
import com.orhon.smartcampus.modules.baseinfo.entity.SchoolcalendarDay;
import com.orhon.smartcampus.modules.baseinfo.entity.SchoolcalendarWeek;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLSchoolCalendarDay;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLSchoolCalendarWeek;
import com.orhon.smartcampus.modules.baseinfo.mm.SchoolCalendarDayMapper;
import com.orhon.smartcampus.modules.baseinfo.mm.SchoolCalendarWeekMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SchoolCalendarWeeksFetcher implements DataFetcher {


	@Autowired
	SchoolcalendarWeekDao schoolcalendarWeekDao;
	
	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {

		List<GQLSchoolCalendarWeek> schoolCalendarWeeks = new ArrayList<>();

		GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);
		String hql = "from SchoolcalendarWeek where deleted_at = null ";
		List<SchoolcalendarWeek> list = schoolcalendarWeekDao.find(hql,null,page.getPage(),page.getLimit());

		for (SchoolcalendarWeek item : list) {
			List<GQLSchoolCalendarDay> gqlSchoolCalendarDay= null;
			if (env.getSelectionSet().contains("data/days")){
				List<SchoolcalendarDay> days = item.getSchoolcalendarDays();
				gqlSchoolCalendarDay = SchoolCalendarDayMapper.MAPPER.toSchoolCalendarDayList(days);
			}

			GQLSchoolCalendarWeek schoolcalendarWeek = SchoolCalendarWeekMapper.MAPPER.toSchoolcalendarWeek(item);
			schoolcalendarWeek.setDays(gqlSchoolCalendarDay);
			schoolCalendarWeeks.add(schoolcalendarWeek);
		}
		Long total = 0L;
		if (env.getSelectionSet().contains("total")){
			total = schoolcalendarWeekDao.getTotalCount(hql);
		}

		return Result.ok().put("data" , schoolCalendarWeeks).put("total" , total);
	}


}
